<?php

    // +----------------------------------------------------------------------
    // | 分类模型
    // +----------------------------------------------------------------------
    // | Copyright (c) 2015-2024 http://www.yicmf.com, All rights reserved.
    // +----------------------------------------------------------------------
    // | Author: 微尘 <yicmf@qq.com>
    // +----------------------------------------------------------------------

    namespace app\event\cms;

    use app\common\event\Base;
    use app\model\ucenter\User as UserModel;
    use app\event\ucenter\Action as ActionEvent;
    use think\db\Where;
    use think\Exception;
    use think\facade\Cache;
    use app\model\cms\Category as CategoryModel;

    class Category extends Base
    {

        public static function getNavLists($pid)
        {
            return CategoryModel::where('pid', $pid)->where('status', 1)->order('sort')->select();
        }

        public static function getIdsWithChild($id)
        {
            return CategoryModel::where('id|pid', $id)->where('status', 1)->column('id');
        }

        /**
         * 获取允许发布的分类
         * @author 微尘 <yicmf@qq.com>
         */
        public static function getAllow($data = [])
        {
            if (isset($data['pattern_id'])) {
                $map['pattern_id'] = ['like', '%' . $data['pattern_id'] . '%'];
            }
			if (isset($data['category_id'])) {
                $map['pid'] = $data['category_id'];
            }else{
				$map['pid'] = 0;
			}
            //            $map['style'] = 2;
            $map['style'] = ['in', '1,2'];
            $map['status'] = 1;
            $cates = CategoryModel::where('pid|id',$data['category_id'])->select();
            $cate = [];
            foreach ($cates as $value) {
                $cate[$value['id']] = $value['title'];
                $children = $value->children()->where('status', 1)->where('style', 1)->select();
                if ($children) {
                    foreach ($children as $child) {
                        $cate[$child['id']] = '   ├' . $child['title'];
                    }
                }
            }
            return $cate;
        }

        /**
         * 检查是否允许发布
         * @param array     $data
         * @param UserModel $user
         * @return bool|string
         * @author 微尘 <yicmf@qq.com>
         * @datetime: 2020/7/5 9:07
         */
        public static function isAllow($data, $user = null)
        {
            $category = CategoryModel::where('id', $data['category_id'])->where('style', 'in', '1,2')->where('status', 1)->find();
            if (!$category) {
                return '当前分类不可发布文档';
            }
            $pattern = $category->patterns()
                ->wherePivot('pattern_id', $data['pattern_id'])->select();
            if (!$pattern) {
                return '发布模型不存在';
            }
            return true;
        }

        /**
         * 获取指定分类的同级分类.
         * @param int  $id 分类ID
         * @param bool $field 查询字段
         * @return array
         */
        public function getSameLevel($id, $field = true)
        {
            $info = $this->info($id, 'pid');
            $map = ['pid' => $info['pid'], 'status' => 1];
            return CategoryModel::field($field)->where(new Where($map))->order('sort')->select();
        }


        /**
         * 获取指定分类子分类ID.
         * @param string $cate 分类ID
         * @return string id列表
         */
        public function getChildrenId($cate)
        {
            $field = 'id,name,pid,title';
            $category = $this->getTree($cate, $field);
            $ids[] = $cate;
            foreach ($category['_'] as $key => $value) {
                $ids[] = $value['id'];
            }
            return implode(',', $ids);
        }

        /**
         * 当前用户权限信息.
         * @param 当前用户的权限组 $arr
         * @return number
         * @author        微尘 <yicmf@qq.com>
         */
        public function getAccessList($arr)
        {
            /* 获取所有分类 */
            $map = ['status' => ['gt', -1], 'pid' => ['eq', 0]];
            //默认目前只取二级分类
            $list = CategoryModel::where($map)->order('sort')->select();
            if (!$list) {
                return false;
            }
            foreach ($list as $keys => $value) {
                if (in_array($value['id'], $arr)) {
                    $list[$keys]['_access'] = 1;
                } else {
                    $list[$keys]['_access'] = 0;
                }
                $map2['pid'] = $value['id'];
                $list2 = CategoryModel::where($map2)->select();
                if ($list2) {
                    foreach ($list2 as $key3 => $value3) {
                        if (in_array($value3['id'], $arr)) {
                            $value3['_access'] = 1;
                        } else {
                            $value3['_access'] = 0;
                        }
                        $list[$keys]['child'][$key3] = $value3;
                        unset($value3);
                    }
                }
            }
            return $list;
        }

        /**
         * 获取分类详细信息.
         * @param mixed $id 分类ID或标识
         * @param mixed $field 查询字段
         * @return Model 分类信息
         * @access public
         * @author 微尘 <yicmf@qq.com>
         */
        public static function info($id, $field = true)
        {
            /* 获取分类信息 */
            if (is_numeric($id)) { //通过ID查询
                $map['id'] = $id;
            } else { //通过标识查询
                $map['name'] = $id;
            }
            return CategoryModel::field($field)->where($map)->find();
        }

        public function getCateTree($condition, $field = '*')
        {
            /**默认获取pid为0的列表**/
            if (!isset($condition['pid'])) {
                $condition['pid'] = 0;
            }
            $lists = CategoryModel::where(new Where($condition))->field($field)->order('sort')->select();
            if (!$lists) {
                return false;
            }
            $cate = [];
            foreach ($lists as $key => $list) {
                $temp = CategoryModel::where(['pid' => $list['id']])->field($field)->order('sort')->select();
                $cate[] = $list;
                if ($temp !== false) {
                    foreach ($temp as $t) {
                        $t['title'] = '&nbsp;&nbsp;&nbsp;├' . $t['title'];
                        $cate[] = $t;
                        $temp2 = CategoryModel::where(['pid' => $t['id']])->field($field)->order('sort')->select();
                        if ($temp2 !== false) {
                            foreach ($temp2 as $t2) {
                                $t['title'] = '├' . $t2['title'];
                                $cate[] = $t2;
                            }
                            unset($temp2);
                        }
                    }
                    unset($temp);
                }
            }
            return $cate;
        }

        /**
         * 获取分类树，指定分类则返回指定分类极其子分类，不指定则返回所有分类树.
         * @param int  $id 分类ID
         * @param bool $field 查询字段
         * @return array 分类树
         */
        public function getTree($id = 0, $field = true)
        {
            /* 获取当前分类信息 */
            if ($id) {
                $info = CategoryModel::info($id);
                $id = $info['id'];
            }
            /* 获取所有分类 */
            $map = ['status' => ['gt', -1]];
            $list = CategoryModel::field($field)->where($map)->order('sort')->select();
            if ($list) {
                $list = list_to_tree($list, $pk = 'id', $pid = 'pid', $child = '_', $root = $id);
            }
            /* 获取返回数据 */
            if (isset($info)) { //指定分类则返回当前分类极其子分类
                $info['_'] = $list;
            } else { //否则返回所有分类
                $info = $list;
            }
            return $info;
        }

        /**
         * 新增更新分类
         * @param array     $param
         * @param UserModel $user
         * @return array
         * @author 微尘 <yicmf@qq.com>
         * @datetime: 2020/5/27 6:56
         */
        public function update($param, $user = null)
        {
            try {
                if (!empty($param['id'])) {
                    // 更新
                    $cate = CategoryModel::where('id', $param['id'])->find();
                    if (!$cate) {
                        throw new Exception('分类不存在');
                    }
                    if (!$cate->save($param)) {
                        throw new Exception('分类更新失败');
                    }
//                    if (!$cate->allowField('pid,title,name,style,is_check,is_recommend,sort,content,description,list_row,display')->save($param)) {
//                        throw new Exception('分类更新失败');
//                    }
                    $pattern_new_ids = explode(',', $param['patterns']);
                    $pattern_has_ids = [];
                    foreach ($cate->patterns()->select() as $item) {
                        $pattern_has_ids[] = $item['id'];
                    }
                    $add = array_diff($pattern_new_ids, $pattern_has_ids);
                    if (count($add) > 0) {
                        $cate->patterns()->saveAll($add);
                    }
                    $reduce = array_diff($pattern_has_ids, $pattern_new_ids);
                    if (count($reduce) > 0) {
                        $cate->patterns()->detach($reduce);
                    }
                    $data['message'] = '分类更新成功';
                } else {
                    $cate = CategoryModel::create($this->request->only('pid,title,name,style,is_check,is_recommend,sort,content,description,list_row,display'));
                    if (!$cate) {
                        throw new Exception('新增分类异常');
                    }
                    $pattern = explode(',', $param['patterns']);
                    if (count($pattern))
                    {
                        $cate->patterns()->saveAll($pattern);
                    }
                    $data['message'] = '分类新增成功';
                }
                //记录行为
                ActionEvent::log('category_update', $cate);
                $data['data'] = $cate;
                $data['code'] = 0;
            } catch (Exception $e) {
                $data['code'] = 1;
                $data['message'] = $e->getMessage();
            }
            return $data;
        }

    }
